<template>
  <div class="el-page el-main el-position">
    <div class="search-card">
      <div class="input-box">
        <div class="searchCard">
          <span class="searchText">农场名称：</span>
          <el-select class="shadowInput" size="mini" v-model="form.farmCode" placeholder="请选择农场" @change="handleTeam">
            <el-option v-for="item in farmList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
        <div class="searchCard">
          <span class="searchText">生产队名称：</span>
          <el-select class="shadowInput" size="mini" clearable v-model="form.teamCode" placeholder="请选择生产队">
            <el-option v-for="item in teamList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
        <el-button class="search" @click="getList">搜索</el-button>
      </div>
      <div class="button-box">
        <el-date-picker size="mini" v-model="timeList" type="datetimerange" :picker-options="pickerOptions"
          format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" align="right" @change="handleFormData">
        </el-date-picker>
      </div>
    </div>
    <el-divider></el-divider>
    <div class="content">
      <el-card class="wide-card" shadow="always">
        <div class="totalLeft">
          <div class="totalLeftImg ">
            <svg-icon class="svg-icon" icon-class="leftTotalOfInStorage" />
            <div class="totalLeftText">
              <div class="totalLeftTextLine1">今日入场净重</div>
              <div class="totalLeftTextLine2">{{ info.today }}<span class="sub">kg</span></div>
            </div>
          </div>
          <div class="totalLeftImg ">
            <svg-icon class="svg-icon" icon-class="bottomTotalOfInStorage" />
            <div class="totalLeftText">
              <div class="totalLeftTextLine1">累计入场净重</div>
              <div class="totalLeftTextLine2">{{ info.total }}<span class="sub">kg</span></div>
            </div>
          </div>
        </div>
        <div class="shuline" style="margin-right: 20px;"></div>
        <div class="rightCanvas">
          <div class="chartMain0">
            <div class="titleLine"></div>
            <div class="titleText">各仓入库净重情况</div>
          </div>
          <div class="contentCanvas">
            <div class="echart-dom" id="carInit" v-if="this.info.series && this.info.series.length"></div>
            <el-empty v-else description="暂无数据"></el-empty>
          </div>
        </div>
      </el-card>
      <el-card class="narrow-card" shadow="always">
        <div class="rightCanvas">
          <div class="chartMain0">
            <div class="titleLine"></div>
            <div class="titleText">入库作物净重分布情况</div>
          </div>
          <div class="contentCanvas">
            <div class="echart-dom" id="carCount" v-if="days && days.length"></div>
            <el-empty v-else description="暂无数据"></el-empty>
          </div>
        </div>
      </el-card>
      <el-card class="margin-card" shadow="always">
        <div class="rightCanvas">
          <div class="chartMain0">
            <div class="titleLine"></div>
            <div class="titleText title-flex">
              <span>入库作物净重统计</span>
              <div class="searchCard">
                <span class="searchText">作物名称：</span>
                <el-select class="shadowInput" size="mini" clearable v-model="cropType" placeholder="请选择作物类型"
                  @change="handleGetCropEchart">
                  <el-option v-for="item in cropList" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </div>
          </div>
          <div class="contentCanvas content-flex">

            <div class="content-item">
              <div class="item-title">不同品质作物</div>
              <div class="insideCanvas">
                <div class="echart-small" id="cropPz2" v-if="mation.cropQuality && mation.cropQuality.length"></div>
                <el-empty description="暂无数据"></el-empty>
              </div>
            </div>
            <div class="content-item">
              <div class="item-title">不同类别作物</div>
              <div class="insideCanvas">
                <div class="echart-small" id="cropLb" v-if="mation.categoryName && mation.categoryName.length"></div>
                <el-empty description="暂无数据"></el-empty>
              </div>
            </div>
            <div class="content-item">
              <div class="item-title">不同品种作物</div>
              <div class="insideCanvas">
                <div class="echart-small" id="cropPz" v-if="mation.cropVarieties && mation.cropVarieties.length"></div>
                <el-empty description="暂无数据"></el-empty>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { selectApi } from '@/api/select'
import { unitSelectApi } from '@/api/dashhboard'
import { formatDate, filterSelect } from '@/utils/methods'
import { getWareHouseApi, cropfbApi, croptjApi, getCropNameApi1 } from '@/api/statisticalReport'
export default {
  data() {
    return {
      form: {
        farmCode: '',
        teamCode: '',
        startTime: '',
        endTime: '',
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      timeList: '',
      farmList: [],
      teamList: [],
      cropList: [],
      cropType: '',
      info: {},
      mation: {},
      days: []
    }
  },
  methods: {
    // 获取下拉框
    // 集团
    async handleGetSelect0() {
      if (this.$status == '0') {
        let res = await unitSelectApi()
        this.farmList = res.data
      } else {
        let res = await selectApi({ type: 'farm_type' })
        this.farmList = res.data.dictItemList
      }
      this.form.farmCode = this.$farmCode
      let res1 = await selectApi({ type: this.form.farmCode })
      if (res1.data != null) {
        this.teamList = res1.data.dictItemList
        this.form.teamCode = this.teamList[0].value
      }
      this.getList()
    },
    // 农场
    async handleGetSelect1() {
      let res = await Promise.all([
        selectApi({ type: 'farm_type' }),
        selectApi({ type: this.$farmCode }),
      ])
      this.farmList = res[0].data.dictItemList.filter(item => item.value == this.$farmCode)
      this.form.farmCode = this.$farmCode
      this.teamList = res[1].data.dictItemList
      this.form.teamCode = this.teamList[0].value
      this.getList()
    },
    // 生产队
    async handleGetSelect2() {
      let res = await Promise.all([
        selectApi({ type: 'farm_type' }),
        selectApi({ type: this.$farmCode }),
      ])
      this.farmList = res[0].data.dictItemList.filter(item => item.value == this.$farmCode)
      this.form.farmCode = this.$farmCode
      this.teamList = res[1].data.dictItemList.filter(item => item.value == this.$teamCode)
      this.form.teamCode = this.$teamCode
      this.getList()
    },
    // 切换农场 更新生产队
    async handleTeam(e) {
      if (e != '000') {
        let res = await selectApi({ type: e })
        this.teamList = res.data.dictItemList
        this.form.teamCode = this.teamList[0].value
      } else {
        this.teamList = []
        this.form.teamCode = ''
      }
    },
    // 获取作物名称
    async handleGetCropName() {
      let res = await getCropNameApi1(this.form)
      if (res.data && res.data.length) {
        this.cropList = filterSelect(res.data)
        this.cropType = this.cropList[0].value
      } else {
        this.cropList = []
        this.cropType = ''
      }

      this.handleGetCropEchart()
    },
    // 获取作物图表
    async handleGetCropEchart() {
      const { data } = await croptjApi({ ...this.form, cropType: this.cropType })
      this.mation = data
      // 品质
      if (data.cropQuality.length) {
        const pz2List = data.cropQuality.map(item => {
          return {
            name: item.name,
            value: item.total
          }
        })
        this.$nextTick(() => {
          this.handlePz2(pz2List)
        })

      }
      // 品种
      if (data.cropVarieties.length) {
        const pzList = data.cropVarieties.map(item => {
          return {
            name: item.name,
            value: item.total
          }
        })
        this.$nextTick(() => {
          this.handlePz(pzList)
        })

      }
      // 类别
      if (data.categoryName.length) {
        const lbList = data.categoryName.map(item => {
          return {
            name: item.name,
            value: item.total
          }
        })
        this.$nextTick(() => {
          this.handleLb(lbList)
        })

      }
    },
    // 获取当天时间
    handleGetTime() {
      // 获取当前日期
      const today = new Date();
      // 设置时间为今天的开始时间 00:00:00
      const startOfDay = formatDate(new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0, 0))
      // 设置时间为今天的结束时间 23:59:59
      const endOfDay = formatDate(new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999))
      this.timeList = [startOfDay, endOfDay]
      this.form.startTime = startOfDay
      this.form.endTime = endOfDay
    },
    // 搜索框时间
    handleFormData() {
      if (this.timeList != null) {
        this.form.startTime = this.timeList[0]
        this.form.endTime = this.timeList[1]
      } else {
        this.form.startTime = ''
        this.form.endTime = ''
      }
      this.getList()
    },
    // 获取表格
    async getList() {
      let res = await Promise.all([
        getWareHouseApi(this.form),
        cropfbApi(this.form),
        this.handleGetCropName(),
      ])
      this.info = res[0].data
      this.days = res[1].data
      this.$nextTick(() => {
        if (this.info.series && this.info.series.length) {
          this.handleCarInit(this.info.xAxis.data, this.info.series, 'carInit')
        }
        if (this.days && this.days.length) {
          const arr = this.days.map(item => {
            return {
              name: item.name,
              value: item.total,
            }
          })
          this.handleCarCount(arr)
        }
      })
    },
    // 车辆入场运粮情况
    handleCarInit(arrX, list, dom) {
      const chartDom = document.getElementById(dom);
      const myChart = echarts.init(chartDom);
      // if (myChart != null && myChart != '' && myChart != undefined) {
      //   myChart.dispose()
      // }
      const series = list.map(item => {
        return {
          name: item.name,
          barWidth: '10',
          data: item.data,
          type: 'bar',
          // stack: 'total',
          showBackground: false,
          backgroundStyle: {
            // 背景色
            color: "rgba(255,255,255,0.1)",
          },
        }
      })
      let option;
      option = {
        title: {
          show: true,
          subtext: 'kg',
          left: '70',
          subtextStyle: {
            fontSize: 12,
            color: '#888'
          }
        },
        tooltip: {
          formatter: function (params) {
            let tooltipContent = ''
            for (let i = 0; i < params.length; i++) {
              tooltipContent += params[i].seriesName + ':' + params[i].value + 'kg' + '<br />'
            }
            return tooltipContent;
          },
          trigger: 'axis',
          textStyle: {
            fontSize: 12,
            color: '#fff'
          },
          axisPointer: {
            type: 'cross'
          },
          borderWidth: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.6)', // 设置背景色为黑色，透明度为0.8
          bodyFontSize: 14, // 设置文字大小
          bodyFontColor: '#fff', // 设置文字颜色为白色
        },
        color: ['#64c0ff', '#91e5d6', '#fb9bab'],
        legend: {
          bottom: '15',
          itemWidth: 20, // 图例标记的宽度
          itemHeight: 10, // 图例标记的高度
        },
        grid: {
          left: '12%',  // 网格距离容器左侧的距离
          right: '10%', // 网格距离容器右侧的距离
          top: '13%',      // 网格距离容器顶部的距离
          bottom: '25%'    // 网格距离容器底部的距离
        },
        xAxis: {
          type: 'category',
          data: arrX,
          axisLabel: {
            show: true,
            color: '#888888',
            fontSize: 14,
            interval: 0
          },
          axisTick: {
            show: false
          },
          splitArea: {
            show: true,
            areaStyle: {
              interval: 0,
              color: '#fff',
              opacity: 0.0

            },
          },
        },
        yAxis: {
          type: 'value',
          splitLine: {  // 坐标轴在 grid 区域中的分隔线
            lineStyle: { // 分隔线
              type: 'dashed', // 线的类型
              color: '#f1f1f1'
            }
          },
          axisLabel: {
            show: true,
            color: '#888888',
            fontSize: 14,
            interval: 0,
          },
        },
        series: series
      };

      option && myChart.setOption(option);
    },
    // 入库作物净重分布情况
    handleCarCount(arr) {
      const chartDom = document.getElementById('carCount');
      const myChart = echarts.init(chartDom);
      let option;

      option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c}kg',
          borderWidth: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.6)', // 设置背景色为黑色，透明度为0.8
          textStyle: {
            fontSize: 12,
            color: '#fff'
          },
        },
        legend: {
          bottom: '5%',
          left: 'center',
          itemWidth: 10, // 图例标记的宽度
          itemHeight: 10, // 图例标记的高度
          textStyle: {
            color: '#888'
          }
        },
        color: ['#64c0ff', '#91e5d6', '#fb9bab'],
        series: [
          {
            type: 'pie',
            // color: ['#5baffd'],
            radius: ['50%', '60%'],
            data: arr,
            emphasis: {
              scale: true, // 开启放大动画
              scaleSize: 15, // 放大的程度
              // itemStyle: {
              //   color: '#64c0ff'
              // }
            },
            label: {
              color: '#888'
            },
            labelLine: {
              length: 20, // 标签线长度
              length2: 30 // 控制第二段线长，一般不用设置，这个就是控制线段最长
            },
          }
        ]
      };

      option && myChart.setOption(option);

    },
    // 不同品质作物
    handlePz2(list) {
      const chartDom = document.getElementById('cropPz2');
      const myChart = echarts.init(chartDom);
      let option;

      option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c}kg',
          borderWidth: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.6)', // 设置背景色为黑色，透明度为0.8
          textStyle: {
            fontSize: 12,
            color: '#fff'
          },
        },
        legend: {
          bottom: '0%',
          left: 'center',
          itemWidth: 10, // 图例标记的宽度
          itemHeight: 10, // 图例标记的高度
          textStyle: {
            color: '#888'
          }
        },
        color: ['#fb9bab', '#91e5d6', '#64c0ff'],
        series: [
          {
            type: 'pie',
            radius: '60%',
            data: list,
            emphasis: {
              scale: true, // 开启放大动画
              scaleSize: 15, // 放大的程度
            },
            label: {
              color: '#888'
            },
            labelLine: {
              length: 20, // 标签线长度
              length2: 30 // 控制第二段线长，一般不用设置，这个就是控制线段最长
            },
          }
        ]
      };

      option && myChart.setOption(option);
    },
    // 不同品种作物
    handlePz(list) {
      const chartDom = document.getElementById('cropPz');
      const myChart = echarts.init(chartDom);
      let option;

      option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c}kg',
          borderWidth: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.6)', // 设置背景色为黑色，透明度为0.8
          textStyle: {
            fontSize: 12,
            color: '#fff'
          },
        },
        legend: {
          bottom: '0%',
          left: 'center',
          itemWidth: 10, // 图例标记的宽度
          itemHeight: 10, // 图例标记的高度
          textStyle: {
            color: '#888'
          }
        },
        color: ['#64c0ff', '#91e5d6', '#fb9bab'],
        series: [
          {
            type: 'pie',
            radius: '60%',
            data: list,
            emphasis: {
              scale: true, // 开启放大动画
              scaleSize: 15, // 放大的程度
            },
            label: {
              color: '#888'
            },
            labelLine: {
              length: 20, // 标签线长度
              length2: 30 // 控制第二段线长，一般不用设置，这个就是控制线段最长
            },
          }
        ]
      };

      option && myChart.setOption(option);
    },
    // 不同类别作物
    handleLb(list) {
      const chartDom = document.getElementById('cropLb');
      const myChart = echarts.init(chartDom);
      let option;

      option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c}kg',
          borderWidth: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.6)', // 设置背景色为黑色，透明度为0.8
          textStyle: {
            fontSize: 12,
            color: '#fff'
          },
        },
        legend: {
          bottom: '0%',
          left: 'center',
          itemWidth: 10, // 图例标记的宽度
          itemHeight: 10, // 图例标记的高度
        },

        series: [
          {
            type: 'pie',
            color: ['#91e5d6', '#64c0ff', '#fb9bab'],
            radius: '60%',
            data: list,
            emphasis: {
              scale: true, // 开启放大动画
              scaleSize: 15, // 放大的程度

            },
            label: {
              color: '#888'
            },
            labelLine: {
              length: 20, // 标签线长度
              length2: 30 // 控制第二段线长，一般不用设置，这个就是控制线段最长
            },
          }
        ]
      };

      option && myChart.setOption(option);
    },
  },
  mounted() {
    if (this.$status == '0') {
      this.handleGetSelect0()
    }
    if (this.$status == '1') {
      this.handleGetSelect1()
    }
    if (this.$status == '2') {
      this.handleGetSelect2()
    }
    this.handleGetTime()
  }
}
</script>

<style lang='scss' scoped>
.el-page {
  width: 100%;
  height: calc(100vh - 70px);

  .search-card {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;

    .arrow {
      cursor: pointer;
      display: inline-block;
      position: absolute;
      right: -100px;
      font-size: 30px;
      transition: transform 0.3s ease;
    }

    .arrow.down {
      transform: rotate(90deg);
    }
  }

  .input-box {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    transition: height 0.2s ease-in-out;
  }

  ::v-deep .el-card__body {
    padding: 10px !important;
    display: flex;
    // align-items: center;
  }

  .content {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;


    .totalLeft {
      width: 30%;
      height: 300px;

      .totalLeftImg {
        position: relative;
        width: 100%;
        height: 120px;

        .svg-icon {
          position: absolute;
          left: 0;
          width: 100%;
          height: 100%;
          z-index: 0;
        }

        .totalLeftText {
          position: absolute;
          top: 20%;
          left: 10%;
          z-index: 1;
          color: #fff;

          .totalLeftTextLine1 {
            font-size: 16px;
          }

          .totalLeftTextLine2 {
            font-size: 32px;
            font-weight: 500;

            .sub {
              font-size: 12px;
            }
          }

        }
      }
    }

    .shuline {
      width: 1px;
      height: 280px;
      margin: 0 3px;
      background: #d1dbe5;
    }

    .rightCanvas {
      flex: 1;
      height: 300px;
      // margin: 0 20px;

      .chartMain0 {
        width: 100%;
        height: 3vh;

        .titleLine {
          width: 4px;
          height: 100%;
          position: relative;
          float: left;
          background: #16745e;
        }

        .titleText {
          color: #4f4f4f;
          font-size: .9em;
          font-weight: 700;
          margin: 0 1.5vw;
          line-height: 3vh;
        }

        .title-flex {
          display: flex;
          align-items: center;
          justify-content: space-between;
          overflow: hidden;
        }
      }

      .contentCanvas {
        width: 100%;
        height: calc(315px - 3vh);

        .echart-dom {
          width: 100%;
          height: 100%;
        }
      }

      .content-flex {
        display: flex;
        align-items: center;
        justify-content: space-around;

        .content-item {
          width: 33%;
          height: 95%;

          .item-title {
            height: 10%;
            line-height: 30px;
            text-align: center;
            color: #0e7b67;
            font-size: 15px;
            font-weight: 700;
          }

          .insideCanvas {
            width: 100%;
            height: 90%;

            .echart-small {
              width: 100%;
              height: 100%;
            }
          }
        }
      }
    }

    .wide-card {
      width: 65%;
      height: 335px;
    }

    .narrow-card {
      width: 34%;
      height: 335px;
    }

    .margin-card {
      margin-top: 15px;
      width: 100%;
      height: 335px;
    }

    ::v-deep .el-card.is-always-shadow {
      box-shadow: 0 2px 7px #8d8d8d;
    }
  }

}
</style>
